// src/store/user.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)

  // 设置用户信息
  // src/store/user.js 需要确保登录时正确设置userId
  const setUser = (userData) => {
    // 确保userData包含有效的userId且为Number类型
    if (!userData?.userId) {
      console.error('用户数据缺少userId字段');
      return;
    }
    userInfo.value = {
      ...userData,
      userId: Number(userData.userId) // 强制转为Number
    };
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
  }

  // 清除用户信息
  const clearUser = () => {
    userInfo.value = null
    localStorage.removeItem('userInfo')
  }

  // 初始化时从localStorage加载
  const initialize = () => {
    const storedUser = localStorage.getItem('userInfo')
    if (storedUser) {
      userInfo.value = JSON.parse(storedUser)
    }
  }

  // 计算属性获取用户名
  const username = computed(() => userInfo.value?.username || '')
  const userId = computed(() => userInfo.value?.userId || '')

  return { userInfo, setUser, clearUser, initialize, username, userId }
})